/**
 *  ClassName: DbHelper.java
 *  created on 2014-05-23
 *  Copyrights 2011-2012 ITVK.CN All rights reserved.
 *  site: http://WWW.ITVK.CN
 *  email: qjyong@gmail.com
 */
package com.lxq.common;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 数据库操作工具类，主要提供了从c3p0连接池中获取数据库连接的方法和关闭数据库连接的方法
 * @author qiujy
 */
public class DbHelper {
	private static Properties props = new Properties();
	private static DataSource pooled;
	
	private DbHelper(){}
	
	static{
		try {
			InputStream is = Thread.currentThread()
					.getContextClassLoader()
					.getResourceAsStream("jdbc.properties");
			
			props.load(is);
			
			//c3p0连接池
			ComboPooledDataSource cpds = new ComboPooledDataSource();
			cpds.setDriverClass(props.getProperty("driverClass")); 
			cpds.setJdbcUrl(props.getProperty("url"));
			cpds.setUser(props.getProperty("user")); 
			cpds.setPassword(props.getProperty("password"));
			
			//c3p0优化参数
			cpds.setAcquireIncrement(Integer.parseInt(props.getProperty("acquireIncrement")));
			cpds.setInitialPoolSize(Integer.parseInt(props.getProperty("initialPoolSize")));
			cpds.setMinPoolSize(Integer.parseInt(props.getProperty("minPoolSize")));                                     
			cpds.setMaxPoolSize(Integer.parseInt(props.getProperty("maxPoolSize")));
			cpds.setMaxIdleTime(Integer.parseInt(props.getProperty("maxIdleTime")));
			cpds.setMaxStatements(Integer.parseInt(props.getProperty("maxStatements")));
			cpds.setCheckoutTimeout(Integer.parseInt(props.getProperty("checkoutTimeout")));
			
			pooled = cpds;
		} catch (IOException e) {
			System.err.println("在classpath下没有找到jdbc.properties文件，请检查!");
			e.printStackTrace();
		} catch (PropertyVetoException e) {
			System.err.println("在classpath下没有找到数据库驱动类，请检查！");
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取数据库连接对象
	 * @return 数据库连接对象
	 * @throws SQLException 获取连接失败时会抛出SQLException
	 */
	public static Connection getConn() throws SQLException{
		Connection conn = null;
		try {
			conn = pooled.getConnection();
		} catch (SQLException e) {
			throw e;
		}
		return conn;
	}
	
	/**
	 * 关闭数据库连接对象
	 * @param conn 要关闭的数据库连接对象
	 */
	public static void close(Connection conn){
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
